package com.facebook.app.client.uiElements;

import java.util.Arrays;

import com.facebook.app.client.ClusteringMethod;
import com.facebook.app.client.ClusteringMethod.ClusteringType;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionModel;
import com.google.gwt.view.client.TreeViewModel;

public class ClusterStrategyChoiceTreeModel implements TreeViewModel {
	
	private final SelectionModel<ClusteringMethod> selectionModel;
	
	public ClusterStrategyChoiceTreeModel(SelectionModel<ClusteringMethod> selectionModel) {
		this.selectionModel = selectionModel;
	}
	
	@Override
	public <T> NodeInfo<?> getNodeInfo(T value) {
		
		if (value == null) {
			
			ListDataProvider<ClusteringType> dataProvider = new ListDataProvider<ClusteringType>(Arrays.asList(ClusteringType.values()));
			
			Cell<ClusteringType> cell = new AbstractCell<ClusteringType>() {
				@Override
				public void render(Context context, ClusteringType value, SafeHtmlBuilder sb) {
					if (value != null) {
						sb.appendEscaped(value.toString());
					}
				}
			};
			
			return new DefaultNodeInfo<ClusteringType>(dataProvider, cell);
		} else if (value instanceof ClusteringType) {
			
			ListDataProvider<ClusteringMethod> dataProvider = new ListDataProvider<ClusteringMethod>();
			
			for (ClusteringMethod method: ClusteringMethod.values()) {
				if (method.getClusteringType() == (ClusteringType) value) {
					dataProvider.getList().add(method);
				}
			}
			
			Cell<ClusteringMethod> cell = new AbstractCell<ClusteringMethod>() {
				@Override
				public void render(Context context, ClusteringMethod value, SafeHtmlBuilder sb) {
					if (value != null) {
						sb.appendEscaped(value.toString());
					}
				}
			};
			
			return new DefaultNodeInfo<ClusteringMethod>(dataProvider, cell, selectionModel, null);
		}
		
	    throw new IllegalArgumentException("Unsupported object type: " + value.getClass().getName());
	}
	
	@Override
	public boolean isLeaf(Object value) {
		return value instanceof ClusteringMethod;
	}

}
